package com.homedo.microservice.open.service.gateway.manager.web.cas;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.homedo.common.bean.data.ResponseData;
import com.homedo.common.bean.data.enums.ResponseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 认证失败处理程序
 */
@Component
public class AwareAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private final ObjectMapper mapper;

    @Autowired
    public AwareAuthenticationFailureHandler(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {

//        response.setStatus(HttpStatus.UNAUTHORIZED.value());//这里不在头里返回 401
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        ResponseData loginResponseData = new ResponseData<>();
        loginResponseData.setResponseEnum(ResponseEnum.UNKNOWN);

        loginResponseData.setRespDesc(e.getMessage());
//        if (e instanceof UsernameNotFoundException) {
        loginResponseData.setResponseEnum(ResponseEnum.USERNAME_NON_EXISTENT);
//        }

        mapper.writeValue(response.getWriter(), loginResponseData);
    }
}
